<?php

declare(strict_types=1);

namespace App\Common\Modular\System\Serve;

use App\Common\Modular\System\Model\CachingModel;
use Core\Basics\BasicsServe;
use Exception;


class CachingServe extends BasicsServe
{
    /**
     * @return CachingModel::class
     */
    public static function model(): string
    {
        return CachingModel::class;
    }

    /**
     * 获取缓存键值
     */
    private function genCachingKey($name): string
    {
        return substr(md5($name), 8, 16);
    }




    /**
     * 设置缓存数据
     * @param string $sign
     * @param $value
     * @param int $ttl
     * @return bool
     */
    public function set(string $sign, $value, int $ttl = 0): bool
    {
        $sign = $this->genCachingKey($sign);
        /**
         * @var CachingModel $caching
         */
        $caching = $this->search(['sign' => $sign])->first();
        if (empty($caching)) {
            $caching = $this->getModel();
        }
        $caching->sign = $sign;
        $caching->expiration_time = $ttl ? (time() + $ttl) : 0;
        $caching->value = ['value' => $value];
        return $caching->save();
    }


    /**
     * 获取缓键值数据
     * @param $sign
     * @param null $default
     * @return mixed
     */
    public function get($sign, $default = null): mixed
    {
        $sign = $this->genCachingKey($sign);
        /**
         * @var $caching CachingModel
         */
        $caching = $this->search(['sign' => $sign])->first();
        if ($caching) {
            if ($caching->expiration_time === 0 || $caching->expiration_time > time()) {
                return $caching->value['value'] ?? $default;
            } else {
                try {
                    $caching->delete();
                    return $default;
                } catch (Exception) {
                    return $default;
                }
            }
        } else {
            return $default;
        }
    }
}